package com.getpebble.android.onboarding.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Analytics.MobileAppOnboarding;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.common.model.LockerApp;
import com.getpebble.android.common.model.PblInstalledAppDataModel;
import com.getpebble.android.http.HttpRequestUtil;
import com.getpebble.android.jsbridge.JsBridgeUtil;
import com.getpebble.android.jsbridge.JsBridgeWebClient;
import com.getpebble.android.main.sections.appstore.constants.AppStoreConstants;
import com.getpebble.android.main.sections.appstore.constants.AppStoreConstants.StoreType;
import com.getpebble.android.onboarding.activity.OnboardingActivity;
import com.getpebble.android.util.HttpUtils;
import com.getpebble.android.webview.WebViewUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class CompatibleAppsWebViewFragment extends PblBaseFragment {
    public static final String TAG = CompatibleAppsWebViewClient.class.getSimpleName();
    private ArrayList<LockerApp> mAppsToLoad = null;
    private Map<UUID, String> mCurrentlyInstalledApps = null;
    private ProgressBar mProgressBar;
    private WebView mWebView;

    private class CompatibleAppsWebViewClient extends JsBridgeWebClient {
        private CompatibleAppsWebViewClient() {
        }

        protected void handleJSBridgeMethods(String methodName, JSONObject methodArgs) {
            if ("bulkLoadAndClose".equals(methodName)) {
                CompatibleAppsWebViewFragment.this.handleBulkLoadAndClose(methodArgs);
            } else if ("skipStep".equals(methodName)) {
                CompatibleAppsWebViewFragment.this.handleSkipStep(methodArgs);
            } else if ("setNavBarTitle".equals(methodName)) {
                CompatibleAppsWebViewFragment.this.handleSetNavBarTitleRequest(methodArgs);
            } else {
                Trace.warning(TAG, "Got unhandled JsBridge request: " + methodName);
            }
        }
    }

    private static final class DebugWebChromeClient extends WebChromeClient {
        private DebugWebChromeClient() {
        }

        public boolean onConsoleMessage(ConsoleMessage cm) {
            Trace.debug(CompatibleAppsWebViewFragment.TAG, String.format("onConsoleMessage - SourceId:%s LineNumber:%d Message:%s", new Object[]{cm.sourceId(), Integer.valueOf(cm.lineNumber()), cm.message()}));
            return true;
        }

        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Trace.debug(CompatibleAppsWebViewFragment.TAG, String.format("onJsAlert - Url:%s Message:%s", new Object[]{url, message}));
            return false;
        }

        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            Trace.debug(CompatibleAppsWebViewFragment.TAG, String.format("onJsConfirm - Url:%s Message:%s", new Object[]{url, message}));
            return false;
        }

        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            Trace.debug(CompatibleAppsWebViewFragment.TAG, String.format("onJsPrompt - Url:%s Message:%s DefaultValue:%s", new Object[]{url, message, defaultValue}));
            return false;
        }
    }

    private class FetchLoadedAppsTask extends PblAsyncTask {
        private Context mContext;
        private Map<UUID, String> mLoadedApps;

        private FetchLoadedAppsTask(Context context) {
            this.mLoadedApps = new HashMap();
            this.mContext = context;
        }

        public boolean doInBackground() {
            Cursor cursor = PblInstalledAppDataModel.fetchInstalledApps(this.mContext.getContentResolver(), PebbleApplication.getConnectedDevice());
            while (cursor.moveToNext()) {
                String uuidString = cursor.getString(cursor.getColumnIndex("uuid"));
                if (uuidString != null) {
                    this.mLoadedApps.put(UUID.fromString(uuidString), cursor.getString(cursor.getColumnIndex("app_name")));
                }
            }
            cursor.close();
            return true;
        }

        private void setLoadedAppsResult() {
            Activity activity = CompatibleAppsWebViewFragment.this.getActivity();
            if (activity != null) {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        CompatibleAppsWebViewFragment.this.setInstalledApps(FetchLoadedAppsTask.this.mLoadedApps);
                    }
                });
            }
        }

        public void onTaskSuccess() {
            setLoadedAppsResult();
        }

        public void onTaskFailed() {
            setLoadedAppsResult();
        }
    }

    public int getLayoutId() {
        return R.layout.fragment_webview;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MobileAppBehavior.logScreenOpened("OnboardingMigration");
        new FetchLoadedAppsTask(getActivity()).submit();
        this.mWebView = (WebView) container.findViewById(R.id.webView);
        this.mWebView.getSettings().setDomStorageEnabled(true);
        this.mProgressBar = (ProgressBar) container.findViewById(R.id.progressbar);
    }

    private void openMigrateWebView() {
        this.mProgressBar.setVisibility(8);
        String url = AppStoreConstants.getStoreUrl(StoreType.ONBOARDING_MIGRATE, null);
        Trace.debug(TAG, "Loading url: " + url);
        loadWebView(url);
    }

    private void loadWebView(String url) {
        WebSettings webSettings = this.mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(2);
        this.mWebView.setWebViewClient(new CompatibleAppsWebViewClient());
        this.mWebView.setWebChromeClient(new DebugWebChromeClient());
        this.mWebView.setLayerType(1, null);
        WebViewUtil.appendPebbleUserAgentStringToWebview(this.mWebView);
        this.mWebView.setBackgroundColor(getResources().getColor(R.color.white));
        this.mWebView.loadUrl(url);
    }

    private void setInstalledApps(Map<UUID, String> installedApps) {
        this.mCurrentlyInstalledApps = installedApps;
        updateAppUuids();
    }

    private void updateAppUuids() {
        String url = PebbleApplication.getBootConfig().getAppUuidMigrateUrl();
        JsonArray appsArray = new JsonArray();
        for (UUID uuid : this.mCurrentlyInstalledApps.keySet()) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("uuid", uuid.toString());
            jsonObject.addProperty("name", (String) this.mCurrentlyInstalledApps.get(uuid));
            appsArray.add(jsonObject);
        }
        JsonObject query = new JsonObject();
        query.add("uuid_upgrades", appsArray);
        HttpRequestUtil.updateAppUuids(getActivity(), url, query, new Runnable() {
            public void run() {
                CompatibleAppsWebViewFragment.this.openMigrateWebView();
            }
        }, 8000);
    }

    private void goToNextFragmentWhenReady(ArrayList<LockerApp> appsToLoad) {
        this.mAppsToLoad = appsToLoad;
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        if (HttpUtils.hasInternetConnection(activity.getApplicationContext())) {
            goToNextFragment(this.mCurrentlyInstalledApps.keySet(), this.mAppsToLoad);
        } else {
            goToNoConnectivityFragment();
        }
    }

    private void goToNextFragment(Set<UUID> currentlyInstalledUuids, ArrayList<LockerApp> appsToLoad) {
        Activity activity = getActivity();
        if (activity != null && (activity instanceof OnboardingActivity)) {
            OnboardingActivity onboardingActivity = (OnboardingActivity) activity;
            Fragment nextFragment = new GrabAppsFragment();
            Bundle args = new Bundle();
            args.putParcelableArrayList("extra_load_app_list", appsToLoad);
            args.putStringArrayList("extra_unload_uuid_list", getAppsToUnload(currentlyInstalledUuids, appsToLoad));
            nextFragment.setArguments(args);
            onboardingActivity.switchScreenFragment(nextFragment);
        }
    }

    private void goToNoConnectivityFragment() {
        Activity activity = getActivity();
        if (activity != null) {
            ((OnboardingActivity) activity).switchToNoConnectivityFragment();
        }
    }

    private ArrayList<String> getAppsToUnload(Set<UUID> currentlyInstalledUuids, ArrayList<LockerApp> appsToLoad) {
        Set<UUID> uuidsToLoad = new HashSet();
        Iterator i$ = appsToLoad.iterator();
        while (i$.hasNext()) {
            uuidsToLoad.add(((LockerApp) i$.next()).getUuid());
        }
        ArrayList<String> uuidsToUnload = new ArrayList();
        for (UUID installedUuid : currentlyInstalledUuids) {
            if (!uuidsToLoad.contains(installedUuid)) {
                uuidsToUnload.add(installedUuid.toString());
            }
        }
        return uuidsToUnload;
    }

    private void handleBulkLoadAndClose(JSONObject methodArgs) {
        Trace.debug(TAG, "Handle bulk load and close: " + methodArgs);
        MobileAppOnboarding.logOnboardingMigrationLoadNowPressed();
        ArrayList<LockerApp> loadAppList = new ArrayList();
        try {
            JSONArray appsJson = methodArgs.getJSONArray("data");
            for (int i = 0; i < appsJson.length(); i++) {
                loadAppList.add((LockerApp) new Gson().fromJson(appsJson.getJSONObject(i).toString(), LockerApp.class));
            }
        } catch (JSONException e) {
            Trace.error(TAG, "Unable to fetch apps to load.", e);
        }
        goToNextFragmentWhenReady(loadAppList);
    }

    private void handleSkipStep(JSONObject methodArgs) {
        Trace.debug(TAG, "Skipping");
        MobileAppOnboarding.logOnboardingMigrationLoadLaterPressed();
        goToNextFragmentWhenReady(new ArrayList());
    }

    private void handleSetNavBarTitleRequest(JSONObject methodArgs) {
        String title = JsBridgeUtil.getTitle(methodArgs);
        if (title != null) {
            setPageTitle(title);
        }
        JsBridgeUtil.notifyLoadResult(this.mWebView, true, methodArgs);
    }

    private void setPageTitle(String title) {
        String upperCaseTitle = title.toUpperCase(Locale.US);
        Activity activity = getActivity();
        if (activity != null) {
            activity.setTitle(upperCaseTitle);
        }
    }
}
